<template>
	<a-modal v-bind="option" class="file-upload-dialog">
		<a-upload
			v-model:file-list="fileList"
			v-bind="uploadOption"
			list-type="picture"
			:show-upload-list="{showPreviewIcon: true, showRemoveIcon: !props.isDetails}">
			<a-empty v-if="fileList?.length === 0" :image="Empty.PRESENTED_IMAGE_SIMPLE" @click.stop />
			<a-button v-show="!props.isDetails" :disabled="props.isDetails" type="primary" ghost block style="border-style: dashed">
				<plus-outlined />
				上传附件
			</a-button>
			<template #iconRender="{file}">
				<svg-icon :icon-class="getFileIcon(file)" />
			</template>
		</a-upload>
		<template #footer>
			<a-button type="primary" :loading="loadingBtn" @click="save">确定</a-button>
		</template>
	</a-modal>
</template>

<script lang="ts" setup>
	import {Img} from 'yuxin-base/src/types'
	import {reactive, ref, toRef, watch, watchEffect} from 'vue'
	import {PlusOutlined} from '@ant-design/icons-vue'
	import {useStore} from '@/store'
	import {authHeader, uploadURL} from 'yuxin-base/src/utils/axios'
	import {Empty, message} from 'ant-design-vue'
	import XEUtils from 'xe-utils'
	import {getFileIcon} from 'yuxin-base/src/utils'
	import fileApi from 'yuxin-base/src/api/file-api'

	const store = useStore()

	const loadingBtn = ref(false)
	const props = withDefaults(
		defineProps<{
			// 新增业务数据时无需设置，业务数据新增后更新图片的bizId，修改时需要设置
			bizId?: string
			// 房源认定后端要求 根据houseId获取附件
			houseId?: string
			// 文件列表
			file?: Img
			files?: Img[]
			// 最大上传数量
			limit?: number
			// 是否支持多张上传
			multiple?: boolean
			// 业务类型
			bizType?: number
			// 单张图片，或者文件大小/M
			fileSize?: number
			visible: boolean
			isDetails?: boolean
		}>(),
		{
			multiple: true
		}
	)

	const loading = ref<boolean>(false)
	const fileList = ref<Img[]>(props.files as [])

	const emits = defineEmits(['update:visible', 'update:files', 'success'])
	const option = reactive({
		title: '上传附件',
		width: '600px',
		centered: true,
		keyboard: false,
		maskClosable: false,
		destroyOnClose: true,
		visible: toRef(props, 'visible'),
		onCancel() {
			emits('success')
			emits('update:visible', false)
		}
	})

	const save = () => {
		emits('success')
		emits('update:visible', false)
	}

	/**
	 * 文件上传业务参数
	 */
	let params = reactive<any>({
		indexNum: 1,
		limit: props.limit,
		bizId: props.bizId
	})

	/**
	 * 文件上传配置
	 */
	const uploadOption = reactive({
		name: 'files',
		multiple: toRef(props, 'multiple'),
		action: uploadURL,
		isImageUrl: () => false,
		headers: authHeader(),
		maxCount: toRef(props, 'limit', props.multiple ? undefined : 1),
		data() {
			for (const key in params) {
				if (params[key] === null || params[key] === undefined) {
					delete params[key]
				}
			}
			return params
		},
		beforeUpload(file: File) {
			loadingBtn.value = true
			params.indexNum = (fileList.value || []).length + 1
			if (props.fileSize) {
				if (file.size / 1024 / 1024 > props.fileSize) {
					return message.error(`上传图片大小${props.fileSize}M以内!`)
				}
			}
		},
		onRemove(file: any) {
			fileApi.removeFile(file.id).then(() => {
				message.success('文件删除成功')
				XEUtils.remove(fileList.value || [], item => file.id === item.id)
				emits('update:files', fileList.value)
			})
		},
		onChange({file, fileList}: any) {
			const {response, status, error} = file
			const index = fileList.findIndex((o: any) => o === file)

			if (status === 'done') {
				loading.value = false
				if (response.code === '200') {
					fileList[index] = response.data
					fileList[index].name = file.name
				} else {
					fileList.splice(index, 1)
					message.error(response.msg)
				}
				loadingBtn.value = false
				emits('update:files', fileList)
			} else if (status === 'error') {
				loadingBtn.value = false
				message.error(`上传失败：${error.status}`)
			}
		}
	})
	watchEffect(() => {
		if (props.bizId) {
			params.bizId = props.bizId

			fileApi.getFileList(props.bizId).then(({data}: {data: Img[]}) => {
				fileList.value = (data || []).map(o => {
					o.name = o.fileOriginName
					return o
				})
				emits('update:files', fileList)
			})
		}
		// 如果有houseId 则更换接口查询
		if (props.houseId) {
			fileApi.getImageList(props.houseId, 20).then(({data}: {data: Img[]}) => {
				fileList.value = (data || []).map(o => {
					o.name = o.fileOriginName
					return o
				})
				emits('update:files', fileList)
			})
		}
	})
	watch(
		() => props.visible,
		() => {
			loadingBtn.value = false
			if (props.visible && !props.bizId) {
				const files = props.files || []
				files.forEach(o => (o.name = o.fileOriginName))
				fileList.value = files
			}
		}
	)
</script>

<style lang="less">
	.file-upload-dialog {
		.ant-modal-body {
			height: 300px;
			overflow: auto;
			padding: 0;

			> span {
				min-height: 100%;
				display: flex;
				flex-direction: column-reverse;
				justify-content: space-between;

				.ant-upload-select {
					position: sticky;
					bottom: 0;
					z-index: 1;
					padding: 12px;
					background: #fff;

					.ant-empty {
						margin: 13% 0;
					}
				}

				.ant-upload-list {
					padding: 8px;
					padding-bottom: 0;
					display: grid;
					grid-template-columns: repeat(2, 50%);

					&:before,
					&:after {
						content: none;
					}

					.ant-upload-list-picture-container {
						margin: 4px;
					}

					.ant-upload-list-item {
						margin: 0;
						padding: 1px;
						//border: none;
						height: 50px;

						.ant-upload-list-item-thumbnail {
							padding: 4px;

							.svg-icon {
								width: 36px;
								height: 36px;
							}
						}
					}
				}
			}
		}
	}
</style>
